package com.asia5b.a5mall.home.fragment

import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5bmall.same.dialog.ApplyShopAgreeDialog
import com.asia5b.a5mall.home.R
import com.asia5b.a5mall.home.adapter.HomeAdapter
import com.asia5b.a5mall.home.databinding.FragmentHomeBinding
import com.asia5b.a5mall.home.listener.HomeAdapterListener
import com.asia5b.a5mall.middleware.base.BaseApplication
import com.asia5b.a5mall.middleware.base.SimpleFragment
import com.asia5b.a5mall.middleware.config.UserRepository
import com.asia5b.a5mall.middleware.logic.viewmodel.home.HomeFragmentVM
import com.asia5b.a5mall.middleware.model.bean.HomeActionIml
import com.asia5b.a5mall.middleware.model.bean.HomeMultiItemEntity
import com.asia5b.a5mall.middleware.model.home.HomeBannerMoel
import com.asia5b.a5mall.middleware.model.home.HomeBlockModel
import com.asia5b.a5mall.middleware.model.home.HomeMenuModel
import com.asia5b.a5mall.middleware.model.shop.AgreementModel
import com.asia5b.a5mall.middleware.utils.*
import com.scwang.smartrefresh.layout.api.RefreshLayout
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.fragment_home.*

/**
 * Created by zhangyuncai on 2020/3/18.
 */
class HomeFragment : SimpleFragment<HomeFragmentVM, FragmentHomeBinding>(), HomeAdapterListener {


    val mDatas = arrayListOf<HomeMultiItemEntity>()
    val mAdapter by lazy { HomeAdapter(simpleLifecycleObserver, mDatas, this) }
    val linearLayoutManager by lazy { LinearLayoutManager(requireContext()) }

    override val viewModelClazz: Class<HomeFragmentVM>
        get() = HomeFragmentVM::class.java

    override fun getDataBinding(container: ViewGroup?): FragmentHomeBinding {
        return FragmentHomeBinding.inflate(layoutInflater, container, false)
    }

    override fun initView() {
        mSmartRefreshLayout = mDataBinding.autoHome
        mDataBinding.autoHome.setEnableLoadMore(false)
        mDataBinding.rvHome.run {
            layoutManager = linearLayoutManager
            adapter = mAdapter
        }


    }

    //搜索框距离右边最大margin
    var marginRightMax = 100//px单位

    //搜索框距离上最大margin
    var marginTopMax = 35//px单位

    //搜索框距离上边最小margin
    var marginTopMin = DisplayUtils.dip2px(BaseApplication.sContext, 5f)//px单位
    override fun initEvent() {
        UserRepository.getInboxOB()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    UserRepository.setNums(tv_home_msg_count, it.unread_message_count)
                }.joinComposite(mCompositeDisposable)

        mDataBinding.viewHomeMsgBaseline.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                val baseline1Top = mDataBinding.viewHomeMsgBaseline.top - status_home.bottom
                val height = ll_home_search_vessel.height
                marginTopMin = baseline1Top - (height / 2)
                if (marginTopMin <= 0) {
                    marginTopMin = 0
                }
                marginRightMax = iv_home_msg.right - iv_home_scan.left + DisplayUtils.dip2px(requireContext(), 10f)
                marginTopMax = ll_home_logo_vessel.height + DisplayUtils.dip2px(requireContext(), 10f)

                //设置顶部headView高度
                val headLayoutParams = marginHeadView.layoutParams
                headLayoutParams.height = cons_home_top_vessel.height
                marginHeadView.layoutParams = headLayoutParams

                //设置搜索栏默认顶部margin
                val searchLayoutParams = mDataBinding.llHomeSearchVessel.layoutParams as ConstraintLayout.LayoutParams
                searchLayoutParams.rightMargin = 0
                searchLayoutParams.topMargin = marginTopMax
                if (searchLayoutParams.topMargin < marginTopMin) {
                    searchLayoutParams.topMargin = marginTopMin
                }
                mDataBinding.llHomeSearchVessel.layoutParams = searchLayoutParams
                mDataBinding.viewHomeMsgBaseline.viewTreeObserver.removeOnGlobalLayoutListener(this)
            }

        })
        mDataBinding.rvHome.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {

                //recyclerview当前滑动距离
                var scrollY = mDataBinding.rvHome.computeVerticalScrollOffset()


//                var scrollY = linearLayoutManager.getScollYDistance()
                //顶部背景图
                view_home_topbg.translationY = scrollY.toFloat() * (-1)


                //防止抖动
                scrollY = (scrollY * 0.65f).toInt()
                dddLog("scrollY:${scrollY}")
                //加快缩减速度
                var scrollRight = (scrollY * 3f).toInt()
                if (scrollRight <= 0) {
                    scrollRight = 0
                } else if (scrollRight > marginRightMax) {
                    scrollRight = marginRightMax
                }
                var scrollTop = scrollY + 0
                if (scrollTop <= 0) {
                    scrollTop = 0
                } else if (scrollTop > marginTopMax) {
                    scrollTop = marginTopMax
                }
                scrollTop = marginTopMax - scrollTop

                val layoutParams = mDataBinding.llHomeSearchVessel.layoutParams as ConstraintLayout.LayoutParams
                layoutParams.rightMargin = scrollRight
                layoutParams.topMargin = scrollTop
                if (layoutParams.topMargin < marginTopMin) {
                    layoutParams.topMargin = marginTopMin
                }
                mDataBinding.llHomeSearchVessel.layoutParams = layoutParams

                //设置logo透明度
                val alpha = scrollTop / (marginTopMax * 1.0f)
                iv_home_asia.alpha = alpha
            }
        })

        //搜索
        onFilterDoubleClick(mDataBinding.llHomeSearchVessel, View.OnClickListener {
            push(ActCons.SearchKeyActivity)
        })
        //扫一扫
        iv_home_scan.setOnClickListener {
            push(ActCons.ScanActivity)
//            ShareUtils.shareWeixin(mActivity)
        }
        //消息
        iv_home_msg.setOnClickListener {
            push(ActCons.MessageActivity, isNeedLogin = true)
        }
        iv_home_asia.setOnClickListener {
//            if (GlobalValue.appType == 0) {
//                push(ActCons.DebugActivity)
//            }
        }
    }

    override fun startObserver() {
        mViewModel.loadFloorLiveData.observe(this, Observer {
            mAdapter.removeAllHeaderView()
            mAdapter.addHeaderView(marginHeadView)
            mAdapter.setNewInstance(it)
            mAdapter.notifyDataSetChanged()
        })
    }

    override fun onClick(item: HomeActionIml) {
        if (item is HomeBlockModel) {
            item.optionBean?.let {
                action("${it.opt_type}", "${it.opt_value}")
            }
        } else if (item is HomeBannerMoel) {
            action(item.operation_type, item.operation_param)
        } else if (item is HomeMenuModel) {
            if (TextUtils.equals("领卷中心", item.navigation_name)) {
                push(ActCons.CouponHallActivity)
            } else if (item.url?.endsWith("shop/apply")) {
                if (UserRepository.isLogin(requireContext())) {
                    if (UserRepository.getUserInfo().haveShop() && false) {
                        startShopActivity(requireContext(), UserRepository.getUserInfo().shop_id)
                    } else {
                        mViewModel.getApplyShopAgreeContent(Consumer<AgreementModel> {
                            if (TextUtils.isEmpty(it.content)) {
                                showMessage(getString(R.string.店铺正在审核中))
                            } else {
                                ApplyShopAgreeDialog(requireContext(), it).apply {
                                    this.setSureClick<Boolean> {
                                        push(ActCons.ApplyShopActivity)
                                    }
                                }.show()
                            }
                        })
                    }
                }
            } else if (item.url?.startsWith("http")) {
                toWeb(item.url, item.navigation_name)
            } else {

            }
        }
    }

    fun action(actionType: String, actionUrl: String) {
        when (actionType) {
            "NONE" -> {//无操作

            }
            "URL" -> {//链接地址
                toWeb(actionUrl)
            }
            "KEYWORD" -> {//关键字

            }
            "GOODS" -> {//商品序号

            }
            "SHOP" -> {//店铺序号

            }
            "CATEGORY" -> {//商品分类

            }
        }
    }

    override fun lazyFetchData() {
        loadFloor()
    }

    val marginHeadView by lazy {
        val view = View(requireContext())
        val layoutParems = RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, 200)
        view.layoutParams = layoutParems
        view
    }

    fun loadFloor() {
        mViewModel.loadFloor(0)

    }


    val listener: (state: Int) -> Unit = {
//        when (it) {
//            LIFE_CYCLE_RESUME -> {
//                dddLog("自动播放")
//                banner.start()
//            }
//            LIFE_CYCLE_PAUSE -> {
//                dddLog("暂停自动播放")
//                banner.stop()
//            }
//        }
    }


    fun toWeb(url: String, title: String = getString(R.string.外部网页)) {
        push(ActCons.WebActivity, {
            //标题
            it.withString("title", title)
            //URL
            it.withString("url", url)
        })
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        mViewModel.loadFloor(1)
    }
}